package com.feini.ktv.svc.controller.om;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feini.ktv.svc.entity.om.*;
import com.feini.ktv.svc.service.om.*;
import com.feini.ktv.svc.util.SysTimeUtil;
import com.podara.skeleton.controller.SkeletonController;
import com.podara.skeleton.log.annotation.LogLogger;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jiangzr
 * @since 2021-04-15
 */
@LogLogger
@RestController
public class OmPayController implements SkeletonController {
    @Autowired
    private IOmPayService payService;

    @Autowired
    private IOmPayDetailService payDetailService;

    @Autowired
    private IOmBoxService boxService;

    @Autowired
    private IOmBoxHService boxHService;

    @Autowired
    private IOmOfferService offerService;

    @Autowired
    private IOmOfferHService offerHService;

    @Autowired
    private IOmOrderService orderService;

    @Autowired
    private IOmOrderHService orderHService;

    @Autowired
    private IOmOrderLineService orderLineService;

    @Autowired
    private IOmOrderLineHService orderLinehService;

    @Autowired
    private IOmItemService itemService;

    @Autowired
    private IOmPriceService priceService;

    @Autowired
    private IOmPriceHService priceHService;

    @GetMapping("/queryPayList")
    public List<OmPay> queryPayList() {
        QueryWrapper<OmPay> payQuery = new QueryWrapper<OmPay>();
        payQuery.eq("order_status", "2");
        List<OmPay> payList = this.payService.list(payQuery);
        return payList;
    }

    @GetMapping("/queryPayByOrderStatus/{orderType}")
    public List<OmPay> queryPayList(@PathVariable("orderType") String orderType) {
        QueryWrapper<OmPay> payQuery = new QueryWrapper<OmPay>();
        payQuery.eq("order_status", orderType);
        List<OmPay> payList = this.payService.list(payQuery);
        return payList;
    }

    @PutMapping("/putOrderPay/{boxId}")
    public boolean postOrderList(@PathVariable("boxId") String boxId, @RequestBody List<Map> orederDatas) {
        boolean secsuce = false;
        if (!Objects.isNull(orederDatas)) {
            QueryWrapper<OmBox> qryBox = new QueryWrapper<OmBox>();
            qryBox.eq("box_id", boxId);
            List<OmBox> boxDcs = boxService.list(qryBox);
            if (null == boxDcs || boxDcs.size() <= 0) {
                throw new NullPointerException("该包厢" + boxId + "订单信息为空!");
            }

            OmBox boxDc = boxDcs.get(0);
            long orderId = boxDc.getOrderId();
            String createOpId = boxDc.getCreateOpId();
            String createOrgId = boxDc.getCreateOrgId();

            QueryWrapper<OmItem> qryItem = new QueryWrapper<OmItem>();
            qryItem.eq("order_id", orderId);
            List<OmItem> items = itemService.list(qryItem);

            secsuce = pushOrderH(orderId);//工单移历史

            long orderLineId = 0;
            if (secsuce) {
                secsuce = pushOrderLineH(orderId, items.get(0).getOrderLineId());//工单项移历史
            }
            if (secsuce) {
                secsuce = pushOmBoxh(boxDc);//包厢移历史
            }
            if (secsuce) {
                secsuce = pushOmOfferH(orderId, orderLineId);//商品实例移历史
            }
            if (secsuce) {
                secsuce = pushOfferPiece(orderId, createOpId, createOrgId);
            }
            if (secsuce) {
                secsuce = pushOmPayH(orderId, createOpId, createOrgId);//支付订单实例移历史
            }
            if (secsuce) {
                secsuce = pushOmPayDetailH(orderId, createOpId, createOrgId, items);//支付订单明细实例移历史
            }
        }
        return secsuce;
    }

    private boolean pushOfferPiece(long orderId, String createOpId, String createOrgId) {
        QueryWrapper<OmPrice> qryPrice = new QueryWrapper<OmPrice>();
        qryPrice.eq("order_id", orderId);

        List<OmPrice> prices = priceService.list(qryPrice);
        boolean issucce = false;
        if (!Objects.isNull(prices)) {
            List<OmPriceH> priceHList = new ArrayList<>();
            for (OmPrice price : prices) {
                OmPriceH priceH = new OmPriceH();
                priceH.setPriceInsKid(price.getPriceInsKid());
                priceH.setPriceInsId(price.getPriceInsId());
                priceH.setOrderId(orderId);
                priceH.setOrderLineId(price.getOrderLineId());
                priceH.setPriceType(price.getPriceType());//定价类型 1营业费,2预存
                priceH.setPriceAct(price.getPriceAct());//支付类型 1收取,2转账,3赠送,4扣减
                priceH.setPriceFee(price.getPriceFee());//优惠价
                priceH.setPriceUnit(price.getPriceUnit());//分
                priceH.setPriceName(price.getPriceName());
                priceH.setPriceVal(price.getPriceVal());//价格
                priceH.setCatType(price.getCatType());//1直接价格 2动态价格
                priceH.setDataStatus("1");
                priceH.setOrderStatus("1");
                priceH.setCreateOpId(createOpId);
                priceH.setCreateOrgId(createOrgId);
                priceH.setCreateDate(price.getCreateDate());
                priceH.setRemark(price.getRemark());
                priceHList.add(priceH);

                issucce = priceService.removeById(price.getPriceInsKid());
            }
            if (issucce) {
                issucce = priceHService.saveBatch(priceHList);
            }
        }
        return issucce;
    }

    private boolean pushOmPayH(long orderId, String createOpId, String createOrgId) {
        LocalDateTime dateTime = LocalDateTime.now();
        OmPay pay = new OmPay();
        pay.setOrderId(orderId);
        pay.setRelaOrderId(0L);
        pay.setCustId(10000001L);
        pay.setPeerChannelId("0");//渠道对接自己默认0
        pay.setBusiCode("1001");//统一支付
        pay.setAccountCode("0");//用户标识
        pay.setAccountType("0");//用户标识手机号
        pay.setRealFee("0");//减免金额
        pay.setCheckStatus("1");//0-不参与对账 1-待对账 2-已对账3-对账差异
        pay.setDataStatus("U");
        pay.setOrderStatus("2");
        pay.setCreateOpId(createOpId);
        pay.setCreateOrgId(createOrgId);
        pay.setCreateDate(dateTime);
        pay.setRemark("结算账单");
        return payService.save(pay);
    }

    private boolean pushOmPayDetailH(long orderId, String createOpId, String createOrgId, List<OmItem> items) {
        long totalShouldFee = 0L;
        long totalActualPrice = 0L;
        long totalDeductPrice = 0L;
        for (OmItem item : items) {
            String shouldFee = item.getShouldFee();
            String actualPrice = item.getActualPrice();
            String deductPrice = item.getDeductPrice();
            if (!Objects.isNull(actualPrice) && StringUtils.isNotEmpty(deductPrice)) {
                totalActualPrice += Long.valueOf(actualPrice);
            }
            if (!Objects.isNull(deductPrice) && StringUtils.isNotEmpty(deductPrice)) {
                totalDeductPrice += Long.valueOf(deductPrice);
            }
        }

        LocalDateTime dateTime = LocalDateTime.now();
        OmPayDetail pay = new OmPayDetail();
        long partitionId = Long.valueOf(SysTimeUtil.getSysDateYYYYMMDDHHMMSS());
        pay.setOrderId(orderId);
        pay.setPartitionId(partitionId);//partition_id分段标识
        pay.setRealFee((int) totalDeductPrice);//减免金额
        pay.setTotalMoney((int) totalActualPrice);
        pay.setCancelTag("U");//U-正常 C-返销 R-冲红
        pay.setOrderStatus("U");
        pay.setCreateOpId(createOpId);
        pay.setCreateOrgId(createOrgId);
        pay.setCreateDate(dateTime);
        pay.setTradeDesc("转换描述");
        pay.setRemark("结算账单");
        return payDetailService.save(pay);
    }

    private boolean pushOmOfferH(long orderId, long orderLineId) {
        QueryWrapper<OmOffer> qryOffer = new QueryWrapper<OmOffer>();
        qryOffer.eq("order_id", orderId);

        List<OmOffer> offers = offerService.list(qryOffer);
        System.out.println(">>>>>>>>>>>>>>>>>>>" + offers);
        boolean flag = false;
        if (!Objects.isNull(offers) && offers.size() > 0) {
            LocalDateTime dateTime = LocalDateTime.now();
            List<OmOfferH> offerHList = new ArrayList<OmOfferH>();
            for (OmOfferH offerMap : offerHList) {
                OmOfferH offer = new OmOfferH();
                long insId = Long.valueOf(SysTimeUtil.getSysDateYYYYMMDDHHMMSS());
                offer.setOfferKid(insId);
                offer.setOfferInsId(offerMap.getOfferInsId());
                offer.setOrderId(orderId);
                offer.setOfferName(offerMap.getOfferName());
                offer.setOfferType(offerMap.getOfferName());
                offer.setOrderLineId(orderLineId);
                offer.setAction("1");
                offer.setAfterDoneCode("1");
                offer.setBeforeDoneCode("1");
                offer.setCustId(10000001L);
                offer.setIsBundle("1");
                offer.setDataStatus("U");
                offer.setOrderStatus("2");
                offer.setCreateOpId(offerMap.getCreateOpId());
                offer.setCreateOrgId(offerMap.getCreateOrgId());
                // offer.setCreateOpId(String.valueOf(offerMap.get("createOpId")));
                // offer.setCreateOrgId(String.valueOf(offerMap.get("createOrgId")));
                offer.setCreateDate(dateTime);
                offer.setRemark("结账");
                offerHList.add(offer);

                offerService.removeById(offerMap.getOfferKid());
            }
            flag = offerHService.saveBatch(offerHList);
        }
        return flag;
    }

    private boolean pushOrderH(long orderId) {
        OmOrder order = orderService.getById(orderId);

        LocalDateTime dateTime = LocalDateTime.now();
        OmOrderH orderh = new OmOrderH();
        orderh.setIntactId(order.getIntactId());
        orderh.setOrderId(orderId);
        orderh.setBusiCode(order.getBusiCode());
        orderh.setCustId(order.getCustId());
        orderh.setIntactContent(order.getIntactContent());
        orderh.setInModeCode(order.getInModeCode());
        orderh.setDataStatus("U");
        orderh.setOrderStatus("2");
        orderh.setCreateOpId(order.getCreateOpId());
        orderh.setCreateOrgId(order.getCreateOrgId());
        orderh.setCreateDate(dateTime);
        orderh.setValidDate(dateTime);
        orderh.setExpireDate(dateTime.withYear(2050).withMonth(12));
        orderh.setRemark("测试");
        boolean isssuces = orderHService.save(orderh);
        if (isssuces) {
            return orderService.removeById(order.getOrderId());
        }
        return false;
    }

    private boolean pushOmBoxh(OmBox boxDc) {
        LocalDateTime dateTime = LocalDateTime.now();
        OmBoxH omBoxh = new OmBoxH();
        Long id = Long.valueOf(SysTimeUtil.getSysDateYYYYMMDDHHMMSS());
        omBoxh.setBoxInsKid(id);
        omBoxh.setOrderLineId(boxDc.getOrderLineId());
        omBoxh.setBoxInsId(boxDc.getBoxInsId());
        omBoxh.setBoxFee(boxDc.getBoxFee());
        omBoxh.setBoxName(boxDc.getBoxName());
        omBoxh.setAction("1");
        omBoxh.setOrderId(boxDc.getOrderId());
        omBoxh.setBoxId(boxDc.getBoxId());
        omBoxh.setDataStatus("U");
        omBoxh.setOrderStatus("2");
        omBoxh.setCreateOpId(boxDc.getCreateOpId());
        omBoxh.setCreateOrgId(boxDc.getCreateOrgId());
        omBoxh.setCreateDate(dateTime);
        omBoxh.setRemark("测试");
        boxHService.save(omBoxh);

       /* UpdateWrapper<OmBox> delete = new UpdateWrapper<>();
        delete.set("box_ins_id", boxDc.getBoxInsId());*/
        return boxService.removeById(boxDc.getBoxInsId());
    }

    public boolean pushOrderLineH(long orderId, long orderLineId) {
        LocalDateTime dateTime = LocalDateTime.now();
        OmOrderLineH orderLine = new OmOrderLineH();
        orderLine.setOrderId(orderId);
        orderLine.setIntactId(201L);
        orderLine.setOrderLineId(orderLineId);
        orderLine.setIntactItemContent("om_order_line_h");
        orderLine.setAccessNum("13974970860");
        orderLine.setDataStatus("0");
        orderLine.setOrderStatus("0");
        orderLine.setCreateOpId("jiang");
        orderLine.setCreateOrgId("000000");
        orderLine.setCreateDate(dateTime);
        orderLine.setValidDate(dateTime);
        orderLine.setExpireDate(dateTime.withYear(2050).withMonth(12));
        orderLine.setRemark("测试");
        boolean flag = this.orderLinehService.save(orderLine);
        if (flag) {
            flag = orderLineService.removeById(orderLineId);
        }
        return flag;
    }


}

